//
//  rankListController.m
//  A段项目音乐播放
//
//  Created by 太阳 on 15/5/26.
//  Copyright (c) 2015年 lanou3g.com蓝鸥科技. All rights reserved.
//

#import "rankListController.h"
#import <AFNetworking/AFNetworking.h>
#import <UIImageView+WebCache.h>
#import "SingerModel.h"
#import "playViewController.h"
#import "RankListCell.h"
#import "SingerState.h"
#import "myButton.h"
#import "PendulumView.h"
#import "CollectDatabase.h"
#import "DataBaseHandler.h"

@interface rankListController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>

@end

@implementation rankListController
- (void)dealloc
{
    [_myTableView release];
    [_myModel release];
    [_modelArray release];
    [_address release];
    [_details release];
    [_myscrollview release];
    [_headerImaggeView release];
    [_myview release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (void)loadView
{
    [super loadView];
    UIColor *ballColor = [UIColor colorWithRed:0.47 green:0.60 blue:0.89 alpha:1];
    PendulumView *pendulum = [[PendulumView alloc] initWithFrame:self.view.bounds ballColor:ballColor];
    [self.myTableView addSubview:pendulum];
    
}
- (void)viewDidLoad
{
    [super viewDidLoad];

    [self builtTableView];
    [self requestNet];
}
- (void)addscrollview
{
    self.myscrollview = [[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.width / 1.75)] autorelease];
    self.myscrollview.contentSize = CGSizeMake(0, [UIScreen mainScreen].bounds.size.width / 1.75);
    self.headerImaggeView = [[[UIImageView alloc]initWithFrame:CGRectMake(0, -50, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.width / 1.3)] autorelease];
    [self.headerImaggeView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", self.myModel.pic_url]] placeholderImage:nil options:SDWebImageRetryFailed];
    [self.myscrollview addSubview:self.headerImaggeView];
    [self.myscrollview setBackgroundColor:[UIColor clearColor]];
    
//    UILabel *label = [[[UILabel alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - 200, [UIScreen mainScreen].bounds.size.width / 2.2, 200, 60)] autorelease];
//    label.font = [UIFont systemFontOfSize:15];
//    label.text = self.myModel.details;
//    label.numberOfLines = 0;
//    label.textColor = [UIColor colorWithWhite:0.9 alpha:0.9];
//    [self.myscrollview addSubview:label];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y > 0) {
        NSLog(@"%f", scrollView.contentOffset.y);
        
        
    }
    
    
}
- (void)builtTableView
{
    self.myTableView = [[[UITableView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 64 * 2) style:UITableViewStylePlain] autorelease];
    [self.myTableView setBackgroundColor:[UIColor clearColor]];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    [self.myTableView registerClass:[RankListCell class] forCellReuseIdentifier:@"cell"];
        [self addscrollview];
    self.myTableView.tableHeaderView = self.myscrollview;
    [self.view addSubview:self.myTableView];
}
- (void)requestNet
{
    NSString *strr = [NSString stringWithFormat:@"%@", self.myModel.myId];
    NSString *str = [NSString stringWithFormat:@"http://api.dongting.com/channel/ranklist/%@/songs?page=1&app=ttpod&v=v7.9.1.2015050518&uid=&mid=iPhone5C&f=f320&s=s310&imsi=&hid=&splus=8.4&active=1&net=2&openudid=0494f4176d75510ad1a6542295634d790aad399e&idfa=F46187C9-E6C9-40A1-B881-A47F8EEEB191&utdid=VVtLXHT237sDAJf6mXsYmzAG&alf=201200&bundle_id=com.ttpod.music", strr];
    NSString *address = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    manger.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manger GET:address parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        self.modelArray = [NSMutableArray array];
        NSDictionary *htmldic = [NSJSONSerialization JSONObjectWithData:[NSData dataWithData:responseObject] options:NSJSONReadingMutableContainers error:nil];
        NSArray *dataArray = [htmldic objectForKey:@"data"];
        for (NSDictionary *arraydai in dataArray) {
            SingerModel *model = [[[SingerModel alloc]init]autorelease];
            [model setValuesForKeysWithDictionary:arraydai];
            NSArray *listarray = [arraydai objectForKey:@"auditionList"];
            NSInteger num = [listarray count];
            if (num != 0) {
                NSDictionary *dicc = [listarray objectAtIndex:1];
                [model setValuesForKeysWithDictionary:dicc];
                [self.modelArray addObject:model];
            }
        }
        [self.myTableView reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@", error);
    }];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.modelArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RankListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    SingerModel *model = [self.modelArray objectAtIndex:indexPath.row];
    cell.songnameLabel.text = model.name;
    cell.addButton.row = indexPath.row;
    [cell.addButton addTarget:self action:@selector(buttonaction:) forControlEvents:UIControlEventTouchUpInside];
//    [cell.addButton addButtonAction:self];
    cell.collectButton.row = indexPath.row;
    [cell.collectButton addTarget:self action:@selector(collectButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    cell.singerLabel.text = model.singerName;
    return cell;
}
// 收藏按钮
- (void)collectButtonAction:(myButton *)sender
{
    self.myview = [[[UIView alloc]init] autorelease];
    [self.myview setBackgroundColor:[UIColor colorWithWhite:0.2 alpha:0.8]];
    
    myButton *collectionButton = [myButton buttonWithType:UIButtonTypeSystem];
    collectionButton.layer.borderWidth = 1;
    collectionButton.layer.borderColor = [UIColor lightGrayColor].CGColor;
    [collectionButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [collectionButton setTitle:@"收藏" forState:UIControlStateNormal];
    collectionButton.row = sender.row;
//    [collectionButton setBackgroundColor:[UIColor colorWithRed:0.3 green:1 blue:1 alpha:1]];
    collectionButton.frame = CGRectMake(10, 30, [UIScreen mainScreen].bounds.size.width - 100 - 30, 30);
    [collectionButton addTarget:self action:@selector(collectionbuttonactions:) forControlEvents:UIControlEventTouchUpInside];
    [collectionButton setBackgroundColor:[UIColor colorWithRed:0.15 green:0.7 blue:0.6 alpha:1]];
    [self.myview addSubview:collectionButton];
    self.myview.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.myview.layer.borderWidth = 1;
    NSArray *array = [NSArray array];
        DataBaseHandler *dbHandler = [DataBaseHandler shareInstance];
    array =  [dbHandler selecttableName];
    NSArray *array2 = [NSArray arrayWithArray:array];
    int i = 0;
    for (NSString *str in array2) {
        myButton *button = [myButton buttonWithType:UIButtonTypeSystem];
//        [button setBackgroundColor:[UIColor redColor]];
        [button setTitle:str forState:UIControlStateNormal];
        button.layer.borderColor = [UIColor lightGrayColor].CGColor;
        button.layer.borderWidth = 1;
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.row = sender.row;
        [button setBackgroundColor:[UIColor colorWithRed:0.15 green:0.7 blue:0.6 alpha:1]];
        button.frame = CGRectMake(10, 75 + i * (30 + 20) , [UIScreen mainScreen].bounds.size.width - 100 - 30, 30);
        [button addTarget:self action:@selector(custonaction:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = i + 1;
        [self.myview addSubview:button];
        i++;
    }
    [self.view addSubview:self.myview];
    [self.myview setBackgroundColor:[UIColor whiteColor]];
    self.myview.frame = CGRectMake(50, 150, [UIScreen mainScreen].bounds.size.width - 100, 120 + i * 40);
    
}
//自定歌单
- (void)custonaction:(myButton *)sender
{
    SingerModel *model = [self.modelArray objectAtIndex:sender.row];
    DataBaseHandler *da = [DataBaseHandler shareInstance];
    
    
    NSArray *array = [NSArray array];
    DataBaseHandler *dbHandler = [DataBaseHandler shareInstance];
    array =  [dbHandler selecttableName];
    NSArray *array2 = [NSArray arrayWithArray:array];
    
    NSString *srt = [array2 objectAtIndex:sender.tag - 1];
    
    [da insertmodel:model str:srt];
    UIAlertView *al = [[[UIAlertView alloc] initWithTitle:@"添加成功" message:nil delegate:self cancelButtonTitle:@"返回" otherButtonTitles:nil, nil] autorelease];
    [al show];
    [self.myview removeFromSuperview];
    
}

//收藏dianji
- (void)collectionbuttonactions:(myButton *)inte
{
    SingerModel *model = [self.modelArray objectAtIndex:inte.row];
    [CollectDatabase insertWithModel:model];
    UIAlertView *alvi = [[[UIAlertView alloc]initWithTitle:@"收藏成功" message:nil delegate:self cancelButtonTitle:@"返回" otherButtonTitles:nil, nil] autorelease];
    [alvi show];
    [self.myview removeFromSuperview];
    [self.view setBackgroundColor:[UIColor whiteColor]];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    playViewController *play = [playViewController shareStateOfViewcontroller];
    [play playWithModel:self.modelArray index:indexPath.row];
    
    [self.navigationController presentViewController:play animated:YES completion:nil];
}

- (void)buttonaction:(myButton *)sender
{
    myButton *button = (myButton *)sender;
    SingerModel *model = [self.modelArray objectAtIndex:button.row];
    SingerState *singer = [SingerState shareOfPlayState];
    singer.addNum ++;  //添加数量
    
    [singer.playListAddress insertObject:model atIndex:singer.num + singer.addNum];
    playViewController *play = [[[playViewController alloc]init] autorelease];
    [play.songListTableview reloadData];
    
    NSLog(@"插入%@", model.name);
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}
//- (void)didReceiveMemoryWarning {
//    [super didReceiveMemoryWarning];
//    // Dispose of any resources that can be recreated.
//}
//
//#pragma mark - Table view data source
//
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//#warning Potentially incomplete method implementation.
//    // Return the number of sections.
//    return 0;
//}
//
//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//#warning Incomplete method implementation.
//    // Return the number of rows in the section.
//    return 0;
//}

/*
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];
    
    // Configure the cell...
    
    return cell;
}
*/

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
